package com.adu.springbootdemo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class BaseController {
    // 页数
    public static final String PAGE_NUM = "pageNum";
    // 每页数据量
    public static final String PAGE_SIZE = "pageSize";
    // 排序列
    public static final String ORDER_BY_COLUMN = "orderByColumn";
    // 排序方向：desc||asc
    public static final String IS_ASC = "isAsc";

    /**
     * 设置请求分页数据
     */
    public void startPage() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String pageNumStr = request.getParameter(PAGE_NUM);
        String pageSizeStr = request.getParameter(PAGE_SIZE);
        if (StringUtil.isNotEmpty(pageNumStr) && StringUtil.isNotEmpty(pageSizeStr)) {
            int pageNum = Integer.parseInt(request.getParameter(PAGE_NUM));
            // 最多一页返回20条数据
            int pageSize = Integer.parseInt(request.getParameter(PAGE_SIZE))>20?20:Integer.parseInt(request.getParameter(PAGE_SIZE));
            PageHelper.startPage(pageNum, pageSize);
        }else{
            // 如分页查询未传分页参数，则只返回第一页10条数据
            PageHelper.startPage(1, 10);
        }

    }
}
